package com.keyancompany.zhongbaopingtai.fragment;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.DiscussAreaActivity;
import com.keyancompany.zhongbaopingtai.activity.DocumentShareActivity;
import com.keyancompany.zhongbaopingtai.activity.MyTaskActivity;
import com.keyancompany.zhongbaopingtai.activity.ProjectProgressActivity;
import com.keyancompany.zhongbaopingtai.activity.TaskLabelActivity;
import com.keyancompany.zhongbaopingtai.activity.WeeklyActivity;
import com.keyancompany.zhongbaopingtai.adapter.IndexTeamAdapter;
import com.keyancompany.zhongbaopingtai.adapter.TeamAdapter;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.ListRows;
import com.keyancompany.zhongbaopingtai.model.LoadProjectTeam;
import com.keyancompany.zhongbaopingtai.model.OtherTeam;
import com.keyancompany.zhongbaopingtai.model.TeamUser;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.SPUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.CreateTeamPopup;
import com.keyancompany.zhongbaopingtai.weight.EmptyView;
import com.keyancompany.zhongbaopingtai.weight.IndexTeamPopup;
import com.keyancompany.zhongbaopingtai.weight.MenuPopuWindow;
import com.keyancompany.zhongbaopingtai.weight.NoScorllerListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by firefox on 2016/5/31.
 */
public class TeamFragment extends BaseFragment implements IAsyncHttpResponseHandler {

    @Bind(R.id.listview)
    NoScorllerListView listview;
    @Bind(R.id.empty_view)
    EmptyView emptyView;
    @Bind(R.id.team_value)
    TextView teamValue;
    @Bind(R.id.subject_value)
    TextView subjectValue;

    @Bind(R.id.unfinish)
    TextView unfinish;
    @Bind(R.id.expire)
    TextView expire;
    @Bind(R.id.isdoing)
    TextView isdoing;
    @Bind(R.id.finished)
    TextView finished;
    @Bind(R.id.listrows_state)
    LinearLayout listrowsState;
    @Bind(R.id.current_team)
    TextView currentTeam;

    public static List<TeamUser> list = new ArrayList<TeamUser>();

    private IndexTeamPopup teamPop;
    private CreateTeamPopup createPop;
    private IndexTeamAdapter adapter;
    private String teamCode;
    List<TeamUser> memberList;
    boolean isCaptain = false;
    private int currentPage = 1, total = 1;

//    private List<TeamUser> indexTeamData;//indexTeampop 的填充数据


    @Override
    public int getContentViewId() {
        return R.layout.fragment_team;
    }

    @Override
    public void setUpViews() {
        if (isNetvaiable()) {
            TeamAPI.teamIndex("0", TeamFragment.this, getLoading(R.string.watting_hint));
        }
        listview.setAdapter(new TeamAdapter(context));
    }

    @OnClick(R.id.team_value)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.team_value:
                showHint();
                break;
            default:
                break;
        }
    }

    private void showHint() {
        if (list == null || list.size() < 1) {
            if (createPop == null) {
                createPop = new CreateTeamPopup(getActivity());
                createPop.setCliclSureListener(new MenuPopuWindow.ClickSureListener() {
                    @Override
                    public void clickSureLinstener(String... param) {
                        if (param[0].equals("ok")) {

                        } else {
                            createPop.dismiss();
                        }
                    }
                });
            }
            createPop.showAtLocation(teamValue, Gravity.CENTER, 0, 0);
        } else {
            if (teamPop == null) {
                teamPop = new IndexTeamPopup(getActivity());
                teamPop.setCliclSureListener(new MenuPopuWindow.ClickSureListener() {
                    @Override
                    public void clickSureLinstener(String... param) {
                        //保存当前TeamCode
                        SPUtils.putCommData(context, Constants.TEAM_CODE, TeamFragment.list.get(Integer.valueOf(param[0])).getTeamCode());
                        teamCode = list.get(Integer.valueOf(param[0])).getTeamCode();
                        currentTeam.setText(list.get(Integer.valueOf(param[0])).getTeamName());
                        // Then load team member.
                        //TODO 是不是用这个API我还真不确定，为了获取团队所有成员
                        TeamAPI.otherTeam(teamCode, TeamFragment.this, getLoading(R.string.watting_hint));
                    }

                });
            }
            teamPop.showAtLocation(teamValue, Gravity.CENTER, 0, 0);
        }
    }

    @OnItemClick(R.id.listview)
    void itemClick(AdapterView<?> parent, View view, int position, long id) {
        if (TextUtils.isEmpty(currentTeam.getText()) || list.isEmpty()) {
            showHint();
            return;
        }
        if (position == 0) {//我的任务
            IntentUtils.startActivity(context, MyTaskActivity.class, Constants.IS_MY_TASK, 0);
        } else if (position == 1) {//任务看板
            IntentUtils.startActivity(context, MyTaskActivity.class, Constants.IS_MY_TASK, 1);
        } else if (position == 2) {//任务标签
            IntentUtils.startActivity(context, TaskLabelActivity.class);
        } else if (position == 3) {//项目进度
            IntentUtils.startActivity(context, ProjectProgressActivity.class);
        } else if (position == 4) {//周报
            IntentUtils.startActivity(context, WeeklyActivity.class);
        } else if (position == 5) {//讨论区
            IntentUtils.startActivity(context, DiscussAreaActivity.class);
        } else if (position == 6) {//文档分享区
            IntentUtils.startActivity(context, DocumentShareActivity.class);
        }
    }


    @Override
    public void start(int type) {

    }

    @Override
    public void success(int type, String json) {
        switch (type) {
            case TeamAPI.TEAM_INDEX_MARK:
                BaseModel base = JSONObject.parseObject(json, BaseModel.class);

                if (base.result.equals(Constants.SUCESS)) {
                    JSONObject object = JSONObject.parseObject(base.data);
                    currentPage = object.getInteger(Constants.CURRENT);
                    total = object.getInteger(Constants.TOTAL);

                    List<TeamUser> teamIndex = JSONObject.parseArray(JSONObject.parseObject(base.data).getString("list"),
                            TeamUser.class);
                    if (teamIndex != null && teamIndex.size() > 0) {
                        list = teamIndex;
                    } else {
                        T.showShort(getActivity(), base.msg);
                    }
                    if (getUserVisibleHint()) {
                        showHint();
                    }
                }
                break;
            case TeamAPI.LOAD_PROJECT_TEAM_MARK://选中一个 团队后
                BaseModel baseload = JSONObject.parseObject(json, BaseModel.class);
                LoadProjectTeam loadProjectTeam = JSONObject.parseObject(baseload.data, LoadProjectTeam.class);
                if (baseload.result.equals(Constants.SUCCESS)) {
//                    list.get(position).getTeamCode()  currentTeam.setText( );

                    listrowsState.setVisibility(View.VISIBLE);

                    if (loadProjectTeam.getListrows().size() > 0) {
                        for (ListRows rows : loadProjectTeam.getListrows()) {
                            if (rows.getState().equals("0")) {
                                unfinish.setText("待完成" + rows.getCc());
                            } else if (rows.getState().equals("1")) {
                                expire.setText("已过期" + rows.getCc());
                            } else if (rows.getState().equals("2")) {
                                isdoing.setText("进行中" + rows.getCc());
                            } else if (rows.getState().equals("3")) {
                                finished.setText("已完成" + rows.getCc());
                            }
                            //存下 talk（讨论信息）;projectteamuser（团队成员 ）
                            SPUtils.putCommData(getActivity(), Constants.LOAD_PROJECT_TEAM, baseload.data);
                        }
                    }
                } else {
                    T.showShort(getActivity(), baseload.msg);
                }
                break;
            case TeamAPI.OTHER_TEAM_MARK:
                BaseModel baseModel = JSONObject.parseObject(json, BaseModel.class);
                OtherTeam team = JSONObject.parseObject(baseModel.data, OtherTeam.class);
                isCaptain = false; //reload team
                memberList = team.getTeamusers();

                /////////////////////////////////////////

                //Check if current user is leader.
                String currentUser = UserAPI.getUserId();
                for (TeamUser member : memberList) {
                    if (currentUser.equals(member.getUserCode()) && member.getIscaptain().equals("0")) {
                        isCaptain = true;
                        break;
                    }
                }
                break;

        }
    }

    @Override
    public void failed(String error) {
        T.showShort(getActivity(), error);
    }

    @Override
    public void finish(int type) {

    }
}
